package com.yupi.springbootinit.service.impl;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 图片服务实现类
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> searchPicture(String searchText, int pageNum, int pageSize) {
//        计算当前页的起始位置
        long current = (pageNum-1)*pageSize;
        String url = String.format("https://cn.bing.com/images/search?q=%s&form=QBIR&first=%s",searchText,current);
//        String url = String.format("https://cn.bing.com/images/search?q=" + searchText + "&form=QBIR&first=" + current);
//          String url = String.format("https://cn.bing.com/images/search?q=张艺兴&form=QBIR&first=%s",searchText,current);
//        String url = "https://cn.bing.com/images/search?q=张艺兴&first=%s"+ current;
        System.out.println(url);
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据获取异常");
        }
//        可以通过CSS样式选择器来直接选择内容
        Elements elements = doc.select(".iuscp.varh");
        List<Picture> pictures = new ArrayList<>();
        for (Element element : elements) {
//            取图片地址murl
            String m = element.select(".iusc").get(0).attr("m");
            Map<String, Object> map = JSONUtil.toBean(m, Map.class);
            String murl =(String) map.get("murl");
//            System.out.println(murl);
            //            取标题
            String title = element.select(".inflnk").get(0).attr("aria-label");
//            System.out.println(title);
            Picture picture = new Picture();
            picture.setUrl(murl);
            picture.setTitle(title);
            pictures.add(picture);
            if (pictures.size()>=pageSize){
                break;
            }
        }
//        小小封装一下
        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictures);
        return picturePage;
    }
}
